package com.tonann.app.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.tonann.app.VO.MySensor;
import com.tonann.app.conf.AsyncService;
import com.tonann.app.domain.*;
import com.tonann.app.mapper.AppSensorMapper;
import com.tonann.app.mapper.AppSensorMultiValuedMapper;
import com.tonann.app.mapper.AppSensorRecordMapper;
import com.tonann.app.mqtt.dao.DataWriteBody;
import com.tonann.app.mqtt.dao.MQTTSensor;
import com.tonann.app.mqtt.singleServer.MqttConfig;
import com.tonann.app.service.IAppDeviceService;
import com.tonann.app.service.IAppFaultRuleService;
import com.tonann.app.service.IAppGatewayService;
import com.tonann.app.service.IAppSensorService;
import com.tonann.app.utils.FaultRuleUtils;
import com.tonann.app.utils.SensorUtils;
import com.tonann.common.annotation.SensorDataScope;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.constant.UserConstants;
import com.tonann.common.core.page.TableDataInfo;
import com.tonann.common.utils.DateUtils;
import com.tonann.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 传感器管理Service业务层处理
 *
 * @author tonann
 * @date 2022-10-17
 */
@Slf4j
@Service
public class AppSensorServiceImpl implements IAppSensorService {

    @Resource
    private AppSensorMapper appSensorMapper;
    @Resource
    private AppSensorRecordServiceImpl sensorRecordService;
    @Resource
    private IAppDeviceService deviceService;
    @Resource
    private IAppGatewayService gatewayService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private MqttConfig.MqttGateway mqttGateway;
    @Resource
    private MqttConfig mqttConfig;

    @Resource
    private IAppFaultRuleService appFaultRuleService;

    @Resource
    private AppSensorMultiValuedMapper appSensorMultiValuedMapper;

    @Resource
    private AsyncService<AppSensorRecord> asyncService;
    @Resource
    private AppSensorRecordMapper recordMapper;

    /**
     * 查询传感器管理
     *
     * @param sensorId 传感器管理主键
     * @return 传感器管理
     */
    @Override
    public AppSensor selectAppSensorBySensorId(Long sensorId) {
        AppSensor appSensor = SensorUtils.getSensorBySensorId(sensorId);
        if (StringUtils.isNull(appSensor) || appSensor.getDevice() == null) {
            appSensor = appSensorMapper.selectAppSensorBySensorId(sensorId);
            if (appSensor != null) {
                AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(appSensor.getDeviceId());
                appSensor.setDevice(appDevice);
                SensorUtils.setSensorBySensorId(appSensor);
            }
        }
        String value = null;
        Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId());
        if (object != null) {
            if (object instanceof String) {
                value = object.toString();
            }
            if (object instanceof BigDecimal) {
                value = ((BigDecimal) object).toString();
            }
        }
        if (value != null) {
            appSensor.setValue(value);
        }
        return appSensor;
    }

    /**
     * 查询传感器管理列表
     *
     * @param appSensor 传感器管理
     * @return 传感器管理
     */
    @Override
    public List<AppSensor> selectAppSensorList(AppSensor appSensor) {
        return appSensorMapper.selectAppSensorList(appSensor);
    }


    @Override
    public List<AppSensor> selectAppSensorAll(AppSensor appSensor) {
//        List<AppSensor> sensorList = SensorUtils.getSensorCache("list");
//        if (StringUtils.isNull(sensorList) || sensorList.size() == 0) {
        List<AppSensor> sensorList = appSensorMapper.selectAppSensorAll(appSensor);
//            SensorUtils.setSensorCache("list", sensorList);
//        }
        return sensorList;
    }

    /**
     * 新增传感器管理
     *
     * @param appSensor 传感器管理
     * @return 结果
     */
    @Override
    public int insertAppSensor(AppSensor appSensor) {
        if (appSensor.getValue() == null) {
            appSensor.setValue("");
        }
        appSensor.setCreateTime(DateUtils.getNowDate());
        appSensor.setUpdateTime(DateUtils.getNowDate());
        String key = appSensor.getMqttDeviceChannel() + "." + appSensor.getMqttDeviceName() + "." + appSensor.getMqttDeviceTag();
        int row = appSensorMapper.insertAppSensor(appSensor);
        removeDeviceMapKey(appSensor.getDeviceId());
        if (row > 0) {
            if (appSensor.getMqttTopic() != null) {
                if (!MQTTSensor.getInstance().topicSet.contains(appSensor.getMqttTopic())) {
                    try {
                        mqttConfig.addListenTopic(appSensor.getMqttTopic());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    MQTTSensor.getInstance().topicSet.add(appSensor.getMqttTopic());
                }
            }
            MQTTSensor.getInstance().map.put(key, appSensor);
            SensorUtils.setSensorBySensorId(appSensor);
        }
        if (appSensor.getSensorMultiValuedList() != null && !appSensor.getSensorMultiValuedList().isEmpty()) {
            for (AppSensorMultiValued valued : appSensor.getSensorMultiValuedList()) {
                if (valued.getValue() != null && !valued.getValue().isEmpty() && valued.getMeaning() != null && !valued.getMeaning().isEmpty()) {
                    valued.setId(null);
                    valued.setSensorId(appSensor.getSensorId());
                    appSensorMultiValuedMapper.insertAppSensorMultiValued(valued);
                }
            }
        }
        return row;
    }

    /**
     * 修改传感器管理
     *
     * @param appSensor 传感器管理
     * @return 结果
     */
    @Override
    public int updateAppSensor(AppSensor appSensor) {
        appSensor.setUpdateTime(DateUtils.getNowDate());
        String value = null;
        Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId());
        if (object != null) {
            if (object instanceof String) {
                value = object.toString();
            }
            if (object instanceof BigDecimal) {
                value = ((BigDecimal) object).toString();
            }
        }
        String key = appSensor.getMqttDeviceChannel() + "." + appSensor.getMqttDeviceName() + "." + appSensor.getMqttDeviceTag();
        if (MQTTSensor.getInstance().map.get(key) != null) {
            MQTTSensor.getInstance().map.remove(key);
        }
        AppDevice device = deviceService.selectAppDeviceByDeviceId(appSensor.getDeviceId());
        AppGateway gateway = gatewayService.selectAppGatewayByGatewayId(device.getGatewayId());
        AppFaultRule faultRule = appFaultRuleService.selectAppFaultRuleByFaultRuleId(appSensor.getFaultRuleId());
        device.setAppGateway(gateway);
        appSensor.setDevice(device);
        appSensor.setGateway(gateway);
        appSensor.setFaultRule(faultRule);
        appSensor.setRuleName(faultRule.getRuleName());
        if (SensorUtils.getSensorCache("list:deviceId:" + appSensor.getDeviceId()) != null) {
            SensorUtils.delSensorCache("list:deviceId:" + appSensor.getDeviceId());
        }
        MQTTSensor.getInstance().map.put(key, appSensor);
        if (appSensor.getValue() != null && value != null && !appSensor.getValue().equals(value)) {
            if (device != null && gateway != null) {
                if (gateway.getGatewayType().equals("1")) { //处理PLC的值发送的问题
                    if (appSensor.getInputAddress() != null && !appSensor.getInputAddress().trim().equals("")) {
                        String IP = appSensor.getDevice().getAppGateway().getIpAddress();
                        String port = appSensor.getDevice().getAppGateway().getPort();
                        String inputAddress = appSensor.getInputAddress();
                        int address = Integer.parseInt(inputAddress);
                        BigDecimal bigDecimal = new BigDecimal(appSensor.getValue());
                        bigDecimal = bigDecimal.setScale(3, RoundingMode.DOWN);
                        double inputValue = bigDecimal.doubleValue();
                        int v = (int) (inputValue * appSensor.getMagnification());
                        address = address - (address / 10000) * 10000;
                        //TODO
                        //发送PLC
                    }
                } else if (gateway.getGatewayType().equals("2")) {
                    if (appSensor.getMqttWriteTopic() != null
                            && appSensor.getMqttDeviceChannel() != null
                            && appSensor.getMqttDeviceName() != null
                            && appSensor.getMqttDeviceTag() != null) {
                        //发送MQTT
                        List<DataWriteBody> dataBodyList = new ArrayList<>();
                        DataWriteBody dataBody = new DataWriteBody();
                        dataBody.setId(key);
                        dataBody.setV(appSensor.getValue());
                        dataBodyList.add(dataBody);
                        mqttGateway.sendToMqtt(appSensor.getMqttWriteTopic(), false, JSONObject.toJSONString(dataBodyList));
//                        String mqttKey = appSensor.getDevice().getAppGateway().getIpAddress() + ":" + appSensor.getDevice().getAppGateway().getPort();
//                        MqttClientConnect mqttClientConnect = MqttClientConnect.mqttBrokers.get(mqttKey);
//                        try {
//                            mqttClientConnect.pub(appSensor.getMqttWriteTopic(), JSONObject.toJSONString(dataBodyList));
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        Logger log = LoggerFactory.getLogger(AppSensorServiceImpl.class);
                        log.error("mqtt下发数据：" + JSONObject.toJSONString(dataBodyList));
                    }
                }
            }
        }
        if (value == null && appSensor.getValue() != null) {
            if (device != null && gateway != null) {
                if (gateway.getGatewayType().equals("1")) { //处理PLC的值发送的问题
                    if (appSensor.getInputAddress() != null && !appSensor.getInputAddress().trim().equals("")) {
                        String IP = appSensor.getDevice().getAppGateway().getIpAddress();
                        String port = appSensor.getDevice().getAppGateway().getPort();
                        String inputAddress = appSensor.getInputAddress();
                        int address = Integer.parseInt(inputAddress);
                        BigDecimal bigDecimal = new BigDecimal(appSensor.getValue());
                        bigDecimal = bigDecimal.setScale(3, RoundingMode.DOWN);
                        double inputValue = bigDecimal.doubleValue();
                        int v = (int) (inputValue * appSensor.getMagnification());
                        address = address - (address / 10000) * 10000;
                        //TODO
                        //发送PLC
                    }
                } else if (gateway.getGatewayType().equals("2")) {
                    if (appSensor.getMqttWriteTopic() != null
                            && appSensor.getMqttDeviceChannel() != null
                            && appSensor.getMqttDeviceName() != null
                            && appSensor.getMqttDeviceTag() != null) {
                        //发送MQTT
                        List<DataWriteBody> dataBodyList = new ArrayList<>();
                        DataWriteBody dataBody = new DataWriteBody();
                        dataBody.setId(key);
                        dataBody.setV(appSensor.getValue());
                        dataBodyList.add(dataBody);
                        mqttGateway.sendToMqtt(appSensor.getMqttWriteTopic(), false, JSONObject.toJSONString(dataBodyList));
                        Logger log = LoggerFactory.getLogger(AppSensorServiceImpl.class);
                        log.error("mqtt下发数据：" + JSONObject.toJSONString(dataBodyList));
                    }
                }
            }
        }
//        if (sensor != null && Objects.equals(sensor.getIsOn(), "1")) {
//            AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(sensor.getDeviceId());
//            appDevice.setIsRunning(sensor.getValue());
//            deviceService.updateAppDeviceStatus(appDevice);
//        }
        int row = appSensorMapper.updateAppSensor(appSensor);
        removeDeviceMapKey(appSensor.getDeviceId());
        redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId(), appSensor.getValue().toString(), CacheConstants.APP_SENSOR_VALUE_EXPIRE, TimeUnit.SECONDS);
        if (row > 0) {
            SensorUtils.setSensorBySensorId(appSensor);
        }
        appSensorMultiValuedMapper.deleteAppSensorMultiValuedBySensorId(appSensor.getSensorId());
        if (appSensor.getSensorMultiValuedList() != null && !appSensor.getSensorMultiValuedList().isEmpty()) {
            for (AppSensorMultiValued valued : appSensor.getSensorMultiValuedList()) {
                if (valued.getValue() != null && !valued.getValue().isEmpty() && valued.getMeaning() != null && !valued.getMeaning().isEmpty()) {
                    valued.setId(null);
                    valued.setSensorId(appSensor.getSensorId());
                    appSensorMultiValuedMapper.insertAppSensorMultiValued(valued);
                }
            }
        }
        return row;
    }

    @Override
    public int updateAppSensorStatus(AppSensor appSensor) {
        String value = null;
        Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId());
        if (object != null) {
            if (object instanceof String) {
                value = object.toString();
            }
            if (object instanceof BigDecimal) {
                value = ((BigDecimal) object).toString();
            }
        }
        if (appSensor.getValue() != null) {
            if (appSensor.getValue().equals("关")) {
                appSensor.setValue("0");
            } else if (appSensor.getValue().equals("开")) {
                appSensor.setValue("1");
            }
        }
//        if (appSensor.getIsHeight() != null && appSensor.getIsHeight().equals("1")) {
//            AppSensor appSensor1 = new AppSensor();
//            appSensor1.setDeviceId(appSensor.getDeviceId());
//            appSensor1.setUnit("cm");
//            List<AppSensor> list = appSensorMapper.selectAppSensorAll(appSensor1);
//            for (AppSensor sensor : list) {
//                if (!(sensor.getIsHeight() != null && sensor.getIsHeight().equals("1"))) {
//                    Object obj = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId());
//                    if (obj != null) {
//                        if (obj instanceof String) {
//                            value = obj.toString();
//                        }
//                        if (obj instanceof BigDecimal) {
//                            value = ((BigDecimal) obj).toString();
//                        }
//                    }
//                }
//            }
//        }
        String key = appSensor.getMqttDeviceChannel() + "." + appSensor.getMqttDeviceName() + "." + appSensor.getMqttDeviceTag();
        if (value == null || (appSensor.getValue() != null && !appSensor.getValue().equals(value))) {
            if (appSensor.getMqttWriteTopic() != null) {
                //发送MQTT
                List<DataWriteBody> dataBodyList = new ArrayList<>();
                DataWriteBody dataBody = new DataWriteBody();
                dataBody.setId(key);
                dataBody.setV(appSensor.getValue());
                dataBodyList.add(dataBody);
                mqttGateway.sendToMqtt(appSensor.getMqttWriteTopic(), false, JSONObject.toJSONString(dataBodyList));
                Logger log = LoggerFactory.getLogger(AppSensorServiceImpl.class);
                log.error("mqtt下发数据：" + JSONObject.toJSONString(dataBodyList));
            }
        }
        if (MQTTSensor.getInstance().map.get(key) != null) {
            MQTTSensor.getInstance().map.remove(key);
        }
        redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId(), appSensor.getValue().toString(), CacheConstants.APP_SENSOR_VALUE_EXPIRE, TimeUnit.SECONDS);
        MQTTSensor.getInstance().map.put(key, appSensor);
        return 1;
    }

    /**
     * 批量删除传感器管理
     *
     * @param sensorIds 需要删除的传感器管理主键
     * @return 结果
     */
    @Override
    public int deleteAppSensorBySensorIds(Long[] sensorIds) {
        for (Long id : sensorIds) {
            AppSensor sensor = selectAppSensorBySensorId(id);
            if (sensor != null) {
                String key = sensor.getMqttDeviceChannel() + "." + sensor.getMqttDeviceName() + "." + sensor.getMqttDeviceTag();
                if (MQTTSensor.getInstance().map.get(key) != null) {
                    MQTTSensor.getInstance().map.remove(key);
                }
            }
            if (SensorUtils.getSensorCache("list:deviceId:" + sensor.getDeviceId()) != null) {
                SensorUtils.delSensorCache("list:deviceId:" + sensor.getDeviceId());
            }
            redisTemplate.delete(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
        }
        int row = 0;
        for (Long sensorId : sensorIds) {
            appSensorMapper.deleteAppSensorPlaceBySensorId(sensorId);
            appSensorMapper.deleteAppSensorDeptBySensorId(sensorId);
            row = appSensorMapper.deleteAppSensorBySensorId(sensorId);
            if (row > 0) {
                FaultRuleUtils.removeFaultRuleCache("sensorId:" + sensorId);
                SensorUtils.removeSensorCache(sensorId.toString());
            }
        }
        return row;
    }

    /**
     * 删除传感器管理信息
     *
     * @param sensorId 传感器管理主键
     * @return 结果
     */
    @Override
    public int deleteAppSensorBySensorId(Long sensorId) {
        AppSensor sensor = selectAppSensorBySensorId(sensorId);
        if (sensor != null) {
            String key = sensor.getMqttDeviceChannel() + "." + sensor.getMqttDeviceName() + "." + sensor.getMqttDeviceTag();
            if (MQTTSensor.getInstance().map.get(key) != null) {
                MQTTSensor.getInstance().map.remove(key);
            }
            if (SensorUtils.getSensorCache("list:deviceId:" + sensor.getDeviceId()) != null) {
                SensorUtils.delSensorCache("list:deviceId:" + sensor.getDeviceId());
            }
            redisTemplate.delete(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
        }
        int row = 0;
        appSensorMapper.deleteAppSensorPlaceBySensorId(sensorId);
        appSensorMapper.deleteAppSensorDeptBySensorId(sensorId);
        row = appSensorMapper.deleteAppSensorBySensorId(sensorId);
        if (row > 0) {
            FaultRuleUtils.removeFaultRuleCache("sensorId:" + sensorId);
            SensorUtils.removeSensorCache(sensorId.toString());
        }
        return row;
    }

    @Override
    public String checkAppSensorNameUnique(String sensorName) {
        List<AppSensor> sensors = appSensorMapper.checkAppSensorNameUnique(sensorName);
        if (!sensors.isEmpty()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public List<Long> selectAppSensorDeptListBySensorId(Long sensorId) {
        return appSensorMapper.selectAppSensorDeptListBySensorId(sensorId);
    }


    @Override
    public List<Long> selectAppSensorPlaceListBySensorId(Long sensorId) {
        return appSensorMapper.selectAppSensorPlaceListBySensorId(sensorId);
    }


    @Override
    public int authPlaceScope(AppSensor sensor) {
        // 修改传感器信息
        appSensorMapper.updateAppSensor(sensor);
        // 删除传感器与部门关联
        appSensorMapper.deleteAppSensorPlaceBySensorId(sensor.getSensorId());
        // 新增传感器和部门信息（数据权限）
        return insertAppSensorPlace(sensor);
    }

    @Override
    public List<AppSensor> selectAppSensorListByGatewayType(String type) {
        return appSensorMapper.selectAppSensorListByGatewayType(type);
    }

    @Override
    public void updateByModbus(AppSensor resources) {
        AppSensor Sensor = selectAppSensorBySensorId(resources.getSensorId());
        if (Sensor != null && !resources.getValue().equals(Sensor.getValue())) {
//            Sensor.copy(resources);
            Sensor.setValue(resources.getValue());
            Sensor.setUpdateBy(resources.getUpdateBy());
            Sensor.setUpdateTime(resources.getUpdateTime());
            // 清理缓存
//            delCaches(Sensor);
            //更新缓存
//            updateCaches(resources.getSensorId(), SensorMapper.toDto(Sensor),false);
        } else {
            Sensor.setUpdateBy(resources.getUpdateBy());
            Sensor.setUpdateTime(resources.getUpdateTime());

        }
        redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_VALUE_KEY + Sensor.getDeviceId() + ":sensorId:" + Sensor.getSensorId(), Sensor.getValue().toString(), CacheConstants.APP_SENSOR_VALUE_EXPIRE, TimeUnit.SECONDS);
        int row = appSensorMapper.updateAppSensor(Sensor);
        if (row > 0) {
//            SensorUtils.setSensorBySensorId(Sensor);
//            MQTTSensor.getInstance().map.put();
//            String tag = Sensor.getMqttDeviceChannel() + "." + Sensor.getMqttDeviceName() + "." + Sensor.getMqttDeviceTag();
//            MQTTSensor.getInstance().map.put(tag, Sensor);
        }
    }

    @Override
    public void updateByModbusList(List<AppSensor> sensorList) {
//        List<AppSensorRecord> recordList = new ArrayList<>();
        Map<Long, AppDevice> deviceMap = new HashedMap<>();
        for (AppSensor sensor : sensorList) {
//            AppSensorRecord sensorRecord = new AppSensorRecord();
//            sensorRecord.setAppSensor(sensor);
//            sensorRecord.setSensorId(sensor.getSensorId());
//            sensorRecord.setValue(sensor.getValue());
//            sensorRecord.setUpdateBy(sensor.getUpdateBy());
//            sensorRecord.setUpdateTime(sensor.getUpdateTime());
//            sensorRecord.setCreateBy(sensor.getCreateBy());
//            sensorRecord.setCreateTime(new Timestamp(new Date().getTime()));
//            sensorRecord.setTime(System.currentTimeMillis());
//            recordList.add(sensorRecord);
            if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsExhaust() != null && sensor.getIsExhaust().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsFresh() != null && sensor.getIsFresh().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsHeight() != null && sensor.getIsHeight().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            } else if (sensor.getIsMute() != null && sensor.getIsMute().equals("1")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            }
            if (sensor.getSensorType().equals("24")) {
                if (StringUtils.contains(sensor.getValue(), ".")) {
                    String val = StringUtils.substringBefore(sensor.getValue(), ".");
                    sensor.setValue(val);
                }
            }
            redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId(), sensor.getValue());
            LocalDateTime localDateTime = LocalDateTime.now();
            ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
            Date date = Date.from(zonedDateTime.toInstant());
            long time = date.getTime();
            redisTemplate.opsForValue().set(CacheConstants.APP_SENSOR_TIME_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId(), Long.toString(time));
            AppDevice appDevice = deviceMap.get(sensor.getDeviceId());
            if (appDevice == null) {
                appDevice = deviceService.selectAppDeviceByDeviceId(sensor.getDeviceId());
            }
            if (sensor.getIsOn().equals("1")) {
                if (appDevice != null && sensor.getValue() != null) {
                    appDevice.setIsRunning(sensor.getValue());
                    if (sensor.getValue().equals("0")) {
                        appDevice.setIsOnline("0");
                    }
                }
            } else if (appDevice != null) {
                if (appDevice.getIsOnline() == null || !appDevice.getIsOnline().equals("1")) {
                    appDevice.setIsOnline("1");
                }
            }
            assert appDevice != null;
            deviceMap.put(appDevice.getDeviceId(), appDevice);
        }
        for (Long id : deviceMap.keySet()) {
            AppDevice appDevice = deviceMap.get(id);
            if (appDevice != null) {
                AppSensor sensor = new AppSensor();
                sensor.setDeviceId(appDevice.getDeviceId());
                sensor.setSensorType("24");
                List<AppSensor> appSensorList = selectAppSensorAllList(sensor);
                if (!appSensorList.isEmpty()) {
                    for (AppSensor appSensor : appSensorList) {
                        String value = null;
                        Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + appSensor.getDeviceId() + ":sensorId:" + appSensor.getSensorId());
                        if (object != null) {
                            if (object instanceof String) {
                                value = object.toString();
                            }
                            if (object instanceof BigDecimal) {
                                value = ((BigDecimal) object).toString();
                            }
                        }
                        if (value != null) {
                            appSensor.setValue(value);
                        }
                        if (appSensor.getValue() != null) {
                            appDevice.setIsRunning(appSensor.getValue());
                            if (appSensor.getValue().equals("0")) {
                                appDevice.setIsOnline("0");
                            }
                        }
                    }
                }
                if (appDevice.getIsOnline().equals("0")) {
                    redisTemplate.opsForValue().set("device:deviceId:isOnline" + appDevice.getDeviceId(), "0", 30, TimeUnit.MINUTES);
                } else {
                    redisTemplate.opsForValue().set("device:deviceId:isOnline" + appDevice.getDeviceId(), "1", 30, TimeUnit.MINUTES);
                }
                deviceService.updateAppDeviceStatus(appDevice);
            }
        }

    }

    @Override
    @SensorDataScope(deptAlias = "s")
    public List<AppSensor> selectAppSensorNameAll(AppSensor appSensor) {
        return appSensorMapper.selectAppSensorNameAll(appSensor);
    }

    @Override
    public TableDataInfo selectValueFromRedis(TableDataInfo tableDataInfo) {
        List<AppSensor> sensorList = (List<AppSensor>) tableDataInfo.getRows();
        List<AppSensor> voList = new ArrayList<>();
        for (AppSensor sensor : sensorList) {
            String value = null;
            Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
            if (object != null) {
                if (object instanceof String) {
                    value = object.toString();
                }
                if (object instanceof BigDecimal) {
                    value = ((BigDecimal) object).toString();
                }
            }
            if (value != null) {
                sensor.setValue(value);
                String updateTime = (String) redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_TIME_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                if (updateTime != null) {
                    try {
                        long time = Long.parseLong(updateTime);
                        Date date = new Date(time);
                        sensor.setUpdateTime(date);
                    } catch (Exception e) {

                    }
                }
            }
            if (sensor.getDeviceId() == 467) {
                System.out.println(sensor.toString());
            }
            voList.add(sensor);
        }
        tableDataInfo.setRows(voList);
        return tableDataInfo;
    }

    @Override
    public void quartzRecordValue() {
        log.info("定时更新传感器值开始");
//        List<AppSensor> sensorList = appSensorMapper.selectAppSensorBaseAll();
        List<AppSensorRecord> appSensorRecordList = new ArrayList<>();
        long start = System.nanoTime();
        Collection<AppSensor> sensorList = MQTTSensor.getInstance().map.values();
        log.info("获取内存中传感器耗时：" + (System.nanoTime() - start));
        start = System.nanoTime();
        Map<String, Long> map = sensorList.stream().collect(Collectors.toMap(
                sensor -> CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId(),
                AppSensor::getSensorId,
                (existing, replacement) -> existing
        ));
        log.info("处理传感器为Map耗时：" + (System.nanoTime() - start));
        start = System.nanoTime();
        Collection<String> collection = map.keySet();
        List<String> keys = collection.stream().collect(Collectors.toList());
        log.info("处理传感器为的MQTT耗时：" + (System.nanoTime() - start));
        start = System.nanoTime();
        List values = redisTemplate.opsForValue().multiGet(keys);
        log.info("redis获取数据耗时：" + (System.nanoTime() - start));
        start = System.nanoTime();
        for (int i = 0; i < values.size(); i++) {
            Object object = values.get(i);
            String value = null;
            if (object != null) {
                if (object instanceof String) {
                    value = object.toString();
                }
                if (object instanceof BigDecimal) {
                    value = ((BigDecimal) object).toString();
                }
            }
            if (value == null) {
                value = "0";
            }
            AppSensorRecord record = new AppSensorRecord();
            record.setValue(value);
            record.setSensorId(map.get(keys.get(i)));
            record.setSaveTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            record.setCreateTime(LocalDateTime.now());
//            appSensorRecordList.add(record);
            redisTemplate.opsForList().leftPush("appsensorrecord", record);
        }
        log.info("构建Record的List数据耗时：" + (System.nanoTime() - start));
        start = System.nanoTime();
//        for (AppSensor sensor : sensorList) {
//            Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
//            String value = null;
//            if (object != null) {
//                if (object instanceof String) {
//                    value = object.toString();
//                }
//                if (object instanceof BigDecimal) {
//                    value = ((BigDecimal) object).toString();
//                }
//            }
//            if (value == null) {
//                value = "0";
//            }
//            AppSensorRecord record = new AppSensorRecord();
//            record.setValue(value);
//            record.setSensorId(sensor.getSensorId());
//            record.setSaveTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
//            record.setCreateTime(LocalDateTime.now());
//            appSensorRecordList.add(record);
//        }
//            不直接插入数据，修改为Redis保存数据队列，在另外一个定时任务中执行数据保存
//        if (!appSensorRecordList.isEmpty()) {
//            asyncService.startMultiThread(appSensorRecordList, recordMapper);
//        }
        log.info("数据库保存数据耗时：" + (System.nanoTime() - start));
        log.info("定时更新传感器值结束");
    }


    @Override
    public void quartzSaveRecordValue() {
        log.info("定时保存传感器值开始");
        List<AppSensorRecord> appSensorRecordList = new ArrayList<>();
        long start = System.nanoTime();
        long startMillis = System.currentTimeMillis();
        try {
            Long size = redisTemplate.opsForList().size("appsensorrecord");
            log.info("获取Redis中传感器队列大小耗时：" + (System.nanoTime() - start));
            start = System.nanoTime();
            if (size != null && size > 0) {
                List<AppSensorRecord> list = redisTemplate.opsForList().range("appsensorrecord", 0, -1);
                log.info("获取Redis中传感器队列耗时：" + (System.nanoTime() - start));
                start = System.nanoTime();
                ListOperations<String, String> listOps = redisTemplate.opsForList();
                while (listOps.size("appsensorrecord") > 0) {
                    listOps.rightPop("appsensorrecord"); // 或者使用leftPop，取决于你的需求和队列的使用方式
                }
                log.info("删除Redis中传感器队列耗时：" + (System.nanoTime() - start));
                start = System.nanoTime();
                if (list != null && !list.isEmpty()) {
                    appSensorRecordList = list;
                    asyncService.startMultiThread(appSensorRecordList, recordMapper);
                }
                log.info("执行数据保存耗时：" + (System.nanoTime() - start));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("定时保存传感器值结束：耗时：" + (System.currentTimeMillis() - startMillis));
    }

    @Override
    public int updateAppSensorFault(AppSensor appSensor) {
        appSensor.setUpdateTime(DateUtils.getNowDate());
        String key = appSensor.getMqttDeviceChannel() + "." + appSensor.getMqttDeviceName() + "." + appSensor.getMqttDeviceTag();
        if (MQTTSensor.getInstance().map.get(key) != null) {
            MQTTSensor.getInstance().map.remove(key);
        }
        if (SensorUtils.getSensorCache("list:deviceId:" + appSensor.getDeviceId()) != null) {
            SensorUtils.delSensorCache("list:deviceId:" + appSensor.getDeviceId());
        }
        MQTTSensor.getInstance().map.put(key, appSensor);
        int row = appSensorMapper.updateAppSensor(appSensor);
        if (row > 0) {
            SensorUtils.setSensorBySensorId(appSensor);
        }
        return row;
    }

    @Override
    public List<AppSensor> selectAppSensorAllListByDeviceIds(List<Long> deviceIds) {
        return appSensorMapper.selectAppSensorAllListByDeviceIds(deviceIds);
    }

    @Override
    public List<AppSensorPlace> selectAppSensorPlaceIdListBySensorIds(List<Long> sensorIdList) {
        return appSensorMapper.selectAppSensorPlaceIdListBySensorIds(sensorIdList);
    }

    @Override
    public List<AppSensorDept> selectAppSensorDeptIdListBySensorIds(List<Long> sensorIdList) {
        return appSensorMapper.selectAppSensorDeptIdListBySensorIds(sensorIdList);
    }

    @Override
    public List<AppSensor> selectAppSensorAllListByDeviceIdsForAPP(List<Long> deviceIds) {
        return appSensorMapper.selectAppSensorAllListByDeviceIdsForAPP(deviceIds);
    }

    @Override
    public void deleteAppSensorByDeviceId(Long deviceId) {
        List<AppSensor> sensorList = appSensorMapper.selectAppSensorListByDeviceId(deviceId);
        for (AppSensor sensor : sensorList) {
            deleteAppSensorBySensorId(sensor.getSensorId());
        }
        removeDeviceMapKey(deviceId);
    }

    @Override
    public List<AppSensor> selectAppSensorAllPureList(AppSensor appSensor) {
        return appSensorMapper.selectAppSensorAllPureList(appSensor);
    }

    @Override
    public List<AppSensor> selectAppSensorAllList(AppSensor appSensor) {
        return appSensorMapper.selectAppSensorAllList(appSensor);
    }

    @Override
    public List<AppSensor> selectAppSensorAllListByDeviceId(Long deviceId) {
        AppSensor appSensor = new AppSensor();
        appSensor.setDeviceId(deviceId);
        return appSensorMapper.selectAppSensorAllList(appSensor);
    }

    @Override
    public List<AppSensor> selectAppSensorAllListByDeviceIdForApp(Long deviceId) {
        return appSensorMapper.selectAppSensorAllListByDeviceIdForApp(deviceId);
    }

    @Override
    public int authDeptScope(AppSensor sensor) {
        // 修改传感器信息
        appSensorMapper.updateAppSensor(sensor);
        // 删除传感器与部门关联
        appSensorMapper.deleteAppSensorDeptBySensorId(sensor.getSensorId());
        // 新增传感器和部门信息（数据权限）
        return insertAppSensorDept(sensor);
    }

    /**
     * 新增传感器部门信息(数据权限)
     *
     * @param sensor 传感器对象
     */
    public int insertAppSensorDept(AppSensor sensor) {
        if (sensor != null && sensor.getSensorId() != null && sensor.getDeptIds() != null) {
            for (Long deptId : sensor.getDeptIds()) {
                appSensorMapper.insertAppSensorDept(sensor.getSensorId(), deptId);
            }
        }
        return 1;
    }


    /**
     * 新增传感器部门信息(数据权限)
     *
     * @param sensor 传感器对象
     */
    public int insertAppSensorPlace(AppSensor sensor) {
        if (sensor != null && sensor.getSensorId() != null && sensor.getPlaceIds() != null) {
            for (Long placeId : sensor.getPlaceIds()) {
                appSensorMapper.insertAppSensorPlace(sensor.getSensorId(), placeId);
            }
        }
        return 1;
    }

    private void removeDeviceMapKey(Long deviceId) {
        try {
            Set<String> deviceSensorKeys = MySensor.getInstance().devicesSensorMap.keySet();
            for (String key : deviceSensorKeys) {
                if (key != null && key.contains(String.valueOf(deviceId))) {
                    MySensor.getInstance().devicesSensorMap.remove(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
